<template>
    <div class="index">
        <el-container>
            <el-header style="width: 90%;height: 70px; margin: auto;">
                <header class="head-nav">
                    <el-row>
                        <el-col :span="6" class="logo-container">
                            <span class="title" style="cursor:pointer;"
                                  @click="$router.push({path:'/home'})">新闻发布系统</span>
                        </el-col>
                        <el-col :span="6" class="search" style="margin-left: 100px;">
                            <el-autocomplete
                                    style="width: 400px"
                                    class="input-with-select"
                                    v-model.trim="input"
                                    clearable
                                    :fetch-suggestions="querySearch"
                                    placeholder="请输入新闻内容"
                                    @select="handleSelect"
                            >
                                <el-button slot="append" @click="search" icon="el-icon-search"></el-button>
                            </el-autocomplete>
                        </el-col>
                        <el-col :span="6" class="user" v-if="!userinfo">
                            <div class="userinfo">
                                <div class="welcome">
                                    <el-button size="small" type="primary" @click="Logindialog = true"
                                    >登录
                                    </el-button
                                    >
                                    <el-button
                                            size="small"
                                            type="success"
                                            @click="Registerdialog = true"
                                    >注册
                                    </el-button
                                    >
                                </div>

                            </div>
                        </el-col>
                        <el-col :span="6" class="user" v-else>
                            <div class="header-right">
                                <img :src="userinfo.avatarUrl" alt=" "/>
                                <el-dropdown @command="handleClick" trigger="click">
       <span class="el-dropdown-link" style="font-size: 22px;color: black">
    {{ userinfo.username }}<i class="el-icon-arrow-down el-icon--right"></i>
  </span>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item v-if="userinfo.role==true">
                                            <el-link href="/adminindex" target="_blank">后台管理</el-link>
                                        </el-dropdown-item>
                                        <el-dropdown-item command='personal'>个人信息</el-dropdown-item>
                                        <el-dropdown-item command='cancel'>退出</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </div>
                        </el-col>
                    </el-row>
                </header>
            </el-header>
            <el-container class="content">
                <el-main style="margin-top: 20px;padding-top: 0">
                    <router-view>
                    </router-view>
                </el-main
                >
            </el-container>
        </el-container>
        <!-- 登录弹窗 -->
        <el-dialog
                title="欢迎登录"
                center
                :visible.sync="Logindialog"
                width="500px"
                custom-class="indexdialog"
                :close-on-click-modal="false"
                @close="closeDialog"
        >
            <el-form :model="form" status-icon :rules="Loginrules" ref="form">
                <el-form-item label="账号:" label-width="60px" prop="username">
                    <el-input v-model="form.username" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码:" label-width="60px" prop="password">
                    <el-input
                            type="password"
                            v-model="form.password"
                            autocomplete="off"
                            show-password
                    ></el-input>
                </el-form-item>
                <el-form-item style="display: flex; justify-content: center">
                    <el-button type="primary" @click="onSubmit('form')"
                    >立即登录
                    </el-button
                    >
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 注册弹窗 -->
        <el-dialog
                title="注册新用户"
                center
                :close-on-click-modal="false"
                :visible.sync="Registerdialog"
                width="500px"
                custom-class="indexdialog"
                @close="RegiscloseDialog"
        >
            <el-form
                    :model="Regisform"
                    status-icon
                    :rules="Regisrules"
                    ref="Regisform"
            >
                <el-form-item label="账号:" label-width="60px" prop="username">
                    <el-input v-model="Regisform.username" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="密码:" label-width="60px" prop="password">
                    <el-input
                            type="password"
                            v-model="Regisform.password"
                            autocomplete="off"
                            show-password
                    ></el-input>
                </el-form-item>
                <el-form-item label="确认密码:" label-width="80px" prop="confirmPassword">
                    <el-input
                            type="checkPass"
                            v-model="Regisform.confirmPassword"
                            autocomplete="off"
                    ></el-input>
                </el-form-item>
                <el-form-item style="display:flex;justify-content: center">
                    <el-button type="primary" @click="onRegis('Regisform')"
                    >立即注册
                    </el-button
                    >
                </el-form-item>
            </el-form>
        </el-dialog>
        <el-drawer
                title="我的信息"
                :visible.sync="drawer"
                @close="drawerClose"
        >
            <el-form style="margin-left: 20px;width: 500px;" label-width="80px" size="small">
                <el-row>
                    <el-col :span="24" style="display: flex;justify-content: center">
                        <el-upload
                                class="avatar-uploader"
                                action="http://localhost:8082/file/upload"
                                :show-file-list="false"
                                :on-success="handleAvatarSuccess"
                        >
                            <img v-if="mineimg" :src="mineimg" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="账户">
                            <el-input v-model="mine.username" autocomplete="off" :disabled="true"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="昵称">
                            <el-input v-model="mine.nickname" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="邮箱">
                            <el-input v-model="mine.email" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="电话">
                            <el-input v-model="mine.phone" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="地址">
                            <el-input v-model="mine.address" type="textarea" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item>
                    <el-button type="primary" @click="save">确 定</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </div>
</template>

<script>
import pubsub from 'pubsub-js'
import {searchNewsByTitle} from '@/api/News'
import {addOrUpdateUser, getUserByName, login, register} from '@/api/User'

export default {
    data() {
        var validatePass2 = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请再次输入密码"));
            } else if (value !== this.Regisform.password) {
                callback(new Error("两次输入密码不一致!"));
            } else {
                callback();
            }
        };
        return {
            restaurants: [],
            input: '',//搜索内容
            value: '',
            user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
            mineimg: "",
            mine: {},
            drawer: false,
            userinfo: {},
            pageNum: 1,
            pageSize: 15,
            Regisrules: {
                username: [
                    {required: true, message: "请输入账号", trigger: "blur"},
                    {min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur"},
                ],
                password: [
                    {required: true, message: "请输入密码", trigger: "blur"},
                    {min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur"},
                ],
                confirmPassword: [{validator: validatePass2, trigger: "blur"}],
            },
            Loginrules: {
                username: [
                    {required: true, message: "请输入账号", trigger: "blur"},
                    {min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur"},
                ],
                password: [
                    {required: true, message: "请输入密码", trigger: "blur"},
                    {min: 1, max: 10, message: "长度在 1 到 10 个字符", trigger: "blur"},
                ],
            },
            form: {
                username: "",
                password: "",
            },
            Regisform: {
                username: "",
                password: "",
                confirmPassword: "",
            },
            Registerdialog: false,
            Logindialog: false,
            activeIndex: '1'
        };
    },
    created() {
        this.getUserinfo();
    },
    methods: {
        querySearch(queryString, cb) {
            this.loadAll();
            var restaurants = this.restaurants;
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
            // 调用 callback 返回建议列表的数据
            cb(results);
        },
        createFilter(queryString) {
            return (restaurant) => {
                return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
            };
        },
        loadAll() {
            //返回从localStorage获取的搜索历史
            var history = JSON.parse(localStorage.getItem("searchHistory"))
            const newArr = history.map((value, index) => {
                return {"value": value, "address": value};
            })
            if (history) {
                this.restaurants = newArr;
            } else {
                this.restaurants = [];
            }
        },
        handleSelect(item) {
            console.log(item);
        },
        async getUser() {
            return (await this.request.get("/user/username/" + this.user.username)).data
        },
        handleAvatarSuccess(res) {
            this.mineimg = res
        },
        //保存个人信息
        save() {
            this.mine.avatarUrl = this.mineimg
            addOrUpdateUser(this.mine).then(res => {
                if (res.code === '200') {
                    this.$message.success('保存成功')
                    // 更新浏览器存储的用户信息
                    this.getUser().then(res => {
                        res.token = JSON.parse(localStorage.getItem("user")).token
                        localStorage.setItem("user", JSON.stringify(res))
                        pubsub.publish("sendMsg");//订阅消息
                        this.drawer = false

                    })
                } else {
                    this.$message.error("保存失败")
                }
            })
        },
        //右侧弹出框关闭回调
        drawerClose() {
            this.mine = {}
            this.mineimg = "";
        },
        getUserinfo() {
            this.userinfo = JSON.parse(localStorage.getItem("user"))
        },
        handleClick(command) {
            if (command === 'cancel') {
                localStorage.removeItem("user")
                this.getUserinfo();
                this.$message.success("退出成功")
            } else if (command === 'personal') {
                // this.$router.push('/personal')
                this.drawer = true;
                this.mine = this.userinfo
                this.mineimg = this.mine.avatarUrl

            }
        },
        search() {
            if (this.input === "") {
                this.$notify({
                    title: '请输入搜索内容',
                    type: 'warning',
                    duration: 500
                });
                return;
            }
            searchNewsByTitle(this.input, this.pageNum, this.pageSize).then(res => {
                if (res) {
                    this.$router.push({path: '/home/searchlist', query: {searchtext: this.input}})
                    pubsub.publish("input");
                    this.$emit('search-event')
                    let searchHistory = JSON.parse(localStorage.getItem("searchHistory")) || [];
                    if (searchHistory.length > 0) {
                        let index = searchHistory.findIndex(item => item === this.input);
                        if (index > -1) {
                            searchHistory.splice(index, 1);
                        }
                    }
                    searchHistory.unshift(this.input);
                    if (searchHistory.length > 6) {
                        searchHistory.pop();
                    }
                    localStorage.setItem("searchHistory", JSON.stringify(searchHistory));
                    this.input = "";
                    this.$notify({
                        title: '搜索成功',
                        type: 'success',
                        duration: 500
                    });
                }
            })
        },
        // 注册按钮
        onRegis(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    register(this.Regisform).then(res => {
                        if (res.code === '200') {
                            this.Registerdialog = false;
                            this.$message.success("注册成功");
                        } else {
                            this.$message.error(res.msg)
                        }
                    })
                } else {
                    this.$message.error("信息输入有误");
                }
            });
        },
        //登录弹窗关闭清空表单
        closeDialog() {
            this.form = {
                username: "",
                password: "",
            };
        },
        //注册弹窗关闭回调
        RegiscloseDialog() {
            this.Regisform = {
                name: "",
                email: "",
                password: "",
                checkPass: "",
            };
        },
        //登录按钮
        onSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    login(this.form).then(res => {
                        if (res.code === '200') {
                            this.$store.dispatch('login', res.data);
                            this.userinfo = res.data
                            localStorage.setItem("user", JSON.stringify(res.data))
                            this.Logindialog = false;
                            // this.$router.push('/adminindex')
                            this.$message.success("登录成功");
                        } else {
                            this.$message.error(res.msg);
                        }
                    })
                } else {
                    this.$message.error("信息输入有误");
                }
            });
        },

    },
};
</script>

<style lang="scss">
.content {
  width: 100%;
  margin: auto;
  height: calc(100vh - 70px);
}

.head-nav {
  width: 100%;
  height: 100%;
  min-width: 600px;
  border-bottom: 1px solid #cdcdcd;
}

.logo-container {
  line-height: 60px;
  min-width: 400px;
}

.title {
  vertical-align: middle;
  font-family: "楷体";
  letter-spacing: 6px;
  font-weight: bold;
  font-size: 35px;
  color: #66b1ff;


}

.search {
  line-height: 60px;
}

.user {
  line-height: 70px;
  text-align: right;
  float: right;
  padding-right: 10px;
}

.welcome {
  display: inline-block;
  width: auto;
  vertical-align: middle;
  padding: 0 5px;
}

.header-right {
  height: 70px;
  display: flex;
  justify-content: end;
  align-items: center;
  user-select: none;
  margin-right: 20px;
}

.header-right img {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  background-color: #fff;
  margin-right: 20px;
  object-fit: cover;
}

.avatar-uploader {
  width: 138px;
  height: 138px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  text-align: center;
  margin-bottom: 20px;
  overflow: hidden;
}

.avatar-uploader .el-upload {
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  line-height: 138px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
}

.indexdialog {
  border-radius: 15px;
  background-color: #f2f2f2;
}

.el-dialog__title {
  line-height: 55px;
  font-size: 22px;
  font-weight: bold;
  color: #5077c5;
}
</style>>
